<script setup lang="ts">
interface Props {
   modelValue: number;
   max: number;
   min?: number;
   label?: string;
}

interface Emits {
   (e: "update:modelValue", value: number): void;
   (e: "change", value: number): void;

}

const props = withDefaults(defineProps<Props>(),{
   min:1
});
const emits = defineEmits<Emits>();

const handleInput = (event: any) => {
   let value: number = event.target.value * 1;
   if (isNaN(value) || value <= 0) {
      value = 1;
   }
   emits("update:modelValue", Math.ceil(value));
   emits("change", Math.ceil(value));
};

const chang = (step: number) => {
   const value: number = props.modelValue + step;
   if (value > props.max || value < props.min) return;
   emits("update:modelValue", value);
   emits("change", value);
};

</script>

<template>
   <div class="count">
      <div class="label">{{ label }}</div>
      <div class="number-box">
         <a @click="chang(-1)">-</a>
         <input type="text" :value="modelValue" @change="handleInput">
         <a @click="chang(+1)">+</a>
      </div>
   </div>
</template>

<style scoped lang="less">
.count {
   display: flex;
   align-items: center;

   .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
   }

   .number-box {
      width: 120px;
      height: 30px;
      border: 1px solid #e4e4e4;
      display: flex;

      > a {
         width: 29px;
         line-height: 28px;
         text-align: center;
         background: #f8f8f8;
         font-size: 16px;
         color: #666;

         &:first-of-type {
            border-right: 1px solid #e4e4e4;
         }

         &:last-of-type {
            border-left: 1px solid #e4e4e4;
         }
      }

      > input {
         width: 60px;
         padding: 0 5px;
         text-align: center;
         color: #666;
      }
   }
}
</style>
